package com.stormragetech.teamwork.spring.interceptor;

import com.alibaba.fastjson.JSON;
import com.stormragetech.teamwork.common.constant.Constants;
import com.stormragetech.teamwork.common.util.AESCrypt;
import com.stormragetech.teamwork.auth.annotation.Perm;
import com.stormragetech.teamwork.module.user.model.TokenInfoModel;
import com.stormragetech.teamwork.module.user.spring.dao.UserDao;
import com.stormragetech.teamwork.module.user.spring.redis.RedisDao;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description: //TODO
 *
 * @author: Xue Bin
 * @version: 1.0.0-SNAPSHOT
 */
@Log4j2
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Value("${aeskey}")
    private String aeskey;

    private final RedisDao redisDao;
    private final UserDao userDao;

    @Autowired
    public AuthInterceptor(RedisDao redisDao, UserDao userDao) {
        Assert.notNull(redisDao, "RedisDao cannot be null !!!");
        Assert.notNull(userDao, "UserDao cannot be null !!!");
        this.redisDao = redisDao;
        this.userDao = userDao;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println();
        log.info("------      权限拦截器开始      ------");
        log.info("------      请求地址: {}      ", request.getServletPath());

        // 获取cookie中权限token
        // Cookie为空
        // 返回权限页面
        //
        Cookie[] cookies = request.getCookies();
        if (null == cookies || cookies.length <= 0) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            log.info("------      验证结果: {}      ", "cookie为空，返回权限");
            log.info("------      权限拦截器结束      ------");
            return false;
        }

        String token = null;
        for (Cookie cookie : cookies) {
            if (Constants.COOKIE_NAME.equals(cookie.getName())) {
                token = cookie.getValue();
                break;
            }
        }

        // cookie中为含有token
        // 返回权限页面
        //
        if (null == token) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            log.info("------      验证结果: {}      ", "cookie不含token，返回权限");
            log.info("------      权限拦截器结束      ------");
            return false;
        }

        // redis中未含有权限token
        // 返回权限页面
        //
        token = AESCrypt.decrypt(token, aeskey);
        String json = redisDao.getKey(token);
        if (null == json || json.length() <= 0) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            log.info("------      验证结果: {}      ", "redis不含token，返回权限");
            log.info("------      权限拦截器结束      ------");
            return false;
        }

        HandlerMethod method = (HandlerMethod) handler;
        String perm = method.getMethodAnnotation(Perm.class).value();

        TokenInfoModel info = JSON.parseObject(json, TokenInfoModel.class);
        boolean isAuth = info.getSign().contains(perm);

        if (!isAuth) {
            log.info("------      验证结果: {}      ", "没有权限");
            log.info("------      权限拦截器结束      ------");
            return true;

        }

        log.info("------      验证结果: {}      ", "通过");
        log.info("------      权限拦截器结束      ------");
        return true;
    }

}
